<template>
    <div>
        <el-card shadow="always" :body-style="{ padding: '20px' }">
            <template #header>
                <el-button type="primary" icon="ele-Plus" @click="showAddDialog" v-has="'btn.Trademark.add'">添加</el-button>
                <el-button type="danger" icon="ele-Minus" @click="deleteSelect">删除选中</el-button>
            </template>
            <!-- card body -->
            <el-table :data="trademarkList" border stripe ref="multipleTableRef" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column type="index" width="80" label="序号" />
                <el-table-column label="品牌名称" prop="tmName" />
                <el-table-column label="品牌logo" prop="logoUrl">
                    <!-- 表格作用域插槽的作用域数据row代表当前行完整数据 $index代表当前数据的下标 -->
                    <template v-slot="{ row }">
                        <el-image style="height: 100px" :src="row.logoUrl" fit="fill" :lazy="true"></el-image>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template v-slot="{ row }">
                        <el-button type="warning" size="small" icon="ele-Edit" @click="showUpdateDialog(row)" v-has="'btn.Trademark.update'">修改</el-button>
                        <el-button type="danger" size="small" icon="ele-Delete" @click="deleteTrademark(row.id)" v-has="'btn.Trademark.remove'">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div>
                <el-pagination
                    v-model:page-size="pageSize"
                    :page-count="pageCount"
                    :pager-count="5"
                    :page-sizes="[3, 5, 7, 9]"
                    v-model:current-page="currentPage"
                    v-model:total="total"
                    layout="total, prev, pager, next, sizes"
                />
            </div>
        </el-card>
        <el-dialog v-model="dialogFormVisible" :title="collectData.id ? '修改品牌' : '添加品牌'">
            <el-form label-width="100px" :model="collectData" :rules="rules" ref="ruleFormRef">
                <el-form-item label="品牌名称" style="width: 80%" prop="tmName">
                    <el-input v-model="collectData.tmName" />
                </el-form-item>
                <el-form-item label="品牌Logo" prop="logoUrl">
                    <el-upload class="avatar-uploader" :action="`${baseUrl}/admin/product/upload`" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="collectData.logoUrl" :src="collectData.logoUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                        <template #tip>
                            <div class="el-upload__tip">上传图片必须是jpg 并且不能大于2M</div>
                        </template>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="addOrUpdateTrademark">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
    name: "Trademark",
});
</script>

<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import { reqDeleteTrademark, reqGetTrademarkList, reqUpdateTrademark, reqAddTrademark, reqGetAllTrademark } from "@/api/trademark";
import type { TrademarkType } from "@/types/trademark";
import { ElMessage, ElMessageBox, type FormInstance, type ElTable } from "element-plus";
import type { UploadProps, FormRules } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { useTrademarkStore } from "@/stores/trademark";

const trademarkList = ref<TrademarkType[]>([]); // 品牌列表
const pageSize = ref<number>(3); // 每页显示的条数
const pageCount = ref<number>(0); // 总页数
const currentPage = ref<number>(1); // 当前页码
const total = ref<number>(0); // 总条数
const trademarkStore = useTrademarkStore(); // 品牌store
/*
 * @description: 获取品牌列表/分页及渲染
 * */
const getTrademarkList = async () => {
    try {
        await trademarkStore.getTrademarkList({
            page: currentPage.value,
            limit: pageSize.value,
        });
        trademarkList.value = trademarkStore.trademarkList;
        pageCount.value = trademarkStore.pages;
        total.value = trademarkStore.total;
    } catch (e) {
        ElMessage.error("获取品牌列表失败");
    }
};
// 监听每页显示条数改变
watch([currentPage, pageSize], () => {
    getTrademarkList();
});
// 挂载完成后获取品牌列表
onMounted(() => {
    getTrademarkList();
});

/*
 * @description: 添加品牌,上传图片
 * */
// 添加品牌打开弹窗
const dialogFormVisible = ref<boolean>(false);
// 上传图片
const imageUrl = ref<string>("");
// 因为上传需要发送请求，且不经过axios，所以需要修改请求地址
const baseUrl = import.meta.env.VITE_API_URL;

const handleAvatarSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
    imageUrl.value = URL.createObjectURL(uploadFile.raw!);

    // 收集地址
    collectData.value.logoUrl = response.data;
};
// 上传图片之前的钩子
const beforeAvatarUpload: UploadProps["beforeUpload"] = rawFile => {
    if (rawFile.type !== "image/jpeg") {
        ElMessage.error("Avatar picture must be JPG format!");
        return false;
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error("Avatar picture size can not exceed 2MB!");
        return false;
    }
    return true;
};
// 收集上传的内容和图片
const collectData = ref<TrademarkType>({
    tmName: "",
    logoUrl: "",
});

/*
 * @description: 删除品牌
 * */
// 删除品牌
const deleteTrademark = async (id: number) => {
    try {
        await ElMessageBox.confirm("确定删除吗？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        }).then(async () => {
            try {
                await reqDeleteTrademark(id);
                ElMessage.success("删除成功");
                getTrademarkList();
            } catch (e) {
                ElMessage({
                    type: "error",
                    message: "删除失败",
                });
            }
        });
    } catch (e) {
        ElMessage({
            type: "info",
            message: "你不删除了????",
        });
    }
};

/*
 * @description: 修改品牌
 * */
// 修改品牌的弹窗
const showUpdateDialog = (item: TrademarkType) => {
    dialogFormVisible.value = true;
    collectData.value = { ...item };
};

// 添加或者修改品牌
const addOrUpdateTrademark = async () => {
    try {
        // 检验表单
        const res = await ruleFormRef.value?.validate();
        if (!res) {
            return;
        }
        // 判断品牌名称是否重复
        const trademarkList = await reqGetAllTrademark();
        const trademarkNameList = trademarkList.map((item: TrademarkType) => item.tmName);
        if (trademarkNameList.includes(collectData.value.tmName)) {
            ElMessage.error("品牌名称重复");
            return;
        }
        // 判断是否有id，有id就是修改，没有就是添加
        if (collectData.value.id) {
            await reqUpdateTrademark(collectData.value);
            ElMessage.success("修改成功");
        } else {
            await reqAddTrademark(collectData.value);
            ElMessage.success("添加成功");
        }
        // closeDialog(); // 关闭弹窗
        dialogFormVisible.value = false;

        getTrademarkList(); // 重新获取品牌列表
    } catch (e) {
        ElMessage.error(collectData.value.id ? "修改失败" : "添加失败");
    }
};
// 打开弹窗
const showAddDialog = () => {
    // 打开弹窗之前重置数据
    collectData.value = {
        tmName: "",
        logoUrl: "",
    };
    dialogFormVisible.value = true;
    ruleFormRef.value?.clearValidate(); // 清除校验
};

/*
 * @description: 表单校验
 * */
const ruleFormRef = ref<FormInstance>(); // 表单实例
const rules = ref<FormRules>({
    tmName: [
        { required: true, message: "请输入品牌名称", trigger: "blur" },
        { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" },
    ],
    logoUrl: [{ required: true, message: "请上传品牌图片", trigger: "change" }],
});

/*
 * 删除选中的品牌
 * */
const multipleSelection = ref<TrademarkType[]>([]);
const handleSelectionChange = (val: TrademarkType[]) => {
    multipleSelection.value = val;
};
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const deleteSelect = () => {
    try {
        // 收集选中的id
        const ids = multipleSelection.value.map((item: TrademarkType) => item.id);
        // 一个个删除
        ids.forEach(item => {
            deleteTrademark(item as number);
        });
        // 重新获取品牌列表
        getTrademarkList();
    } catch (e) {
        ElMessage.error("删除选中失败");
    }
};
</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
